using System.Data;
using MySql.Data.MySqlClient;
using Front._1124;

namespace Front._1230;

public partial class ADDBookForm : Form
{
    public ADDBookForm()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        // 执行数据保存
        using var connection =
            new MySqlConnection(
                "server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;");
        connection.Open();
        string sql =
            "insert  into `book_info`(`isbn`,`book_name`,`author`,`publisher_id`,`publish_date`,`book_category`," +
            "`book_price`,`book_pages`,`book_desc`,`book_status`,`shelf_id`,`purchase_date`,`book_version`,`create_time`) " +
            "values \n(@isbn,@bookName,@author,@publisherId,'2021-06-01','计算机科学',59.80,320,'讲解MySQL基础与实战开发'," +
            "1,1,'2023-01-10','第2版','2025-10-10 10:11:29');";
        // 创建command 对象
        using var command = new MySqlCommand(sql,connection);
        // 绑定参数
        command.Parameters.AddWithValue("isbn", this.isbn.Text);
        command.Parameters.AddWithValue("bookName", this.bookName.Text);
        command.Parameters.AddWithValue("author", this.author.Text);
        command.Parameters.AddWithValue("publisherId", this.publishId.SelectedValue);
        // 执行新增
        int count = command.ExecuteNonQuery();
        if (count > 0)
        {
            MessageBox.Show("新增成功");
            this.DialogResult = DialogResult.OK;
            // 关闭新增窗口
            this.Close();
        }
        else
        {
            MessageBox.Show("新增失败");
        }
    }

    private void Book_Maincs_Load(object sender, EventArgs e)
    {
        Init();
    }

    private void Init()
    {
        // 加载出版社信息
        GetAllPublishers();
        // 加载分类信息
        //GetAllCategories();
        // 加载书架信息
        //GetAllBookShelves();
    }

    private void GetAllPublishers()
    {
        using var connection = new MySqlConnection("server=localhost;port=3306;database=book;user=root;password=root;charset=utf8mb4;AllowPublicKeyRetrieval=True;");
        connection.Open();

        string sql = "select publisher_id,publisher_name from publisher_info;";
        // 创建适配器对象
        MySqlDataAdapter adapter = new MySqlDataAdapter(sql, connection);
        // 创建数据集
        DataSet dataSet = new DataSet();
        // 填充数据
        adapter.Fill(dataSet, "publisher_info");
        // 绑定数据
        DataTable? dataTable = dataSet.Tables["publisher_info"];
        // 插入全部行
        DataRow row = dataTable.NewRow();
        row[0] = 0;
        row[1] = "全部";
        dataTable.Rows.InsertAt(row, 0);
        // 绑定数据
        this.publishId.DataSource = dataTable;
        this.publishId.ValueMember = dataTable.Columns[0].ColumnName;
        this.publishId.DisplayMember = dataTable.Columns[1].ColumnName;
    }
}

